'use strict'
// 15日 2.0版本
const router = require('koa-router')()
const fs = require('fs')

// 获取所有路由定义文件
function getRouteFile(filePath) {
    let files = fs.readdirSync(filePath)
    let routerfile = files.filter(item => {
        return item.endsWith('.js') && item !== 'index.js'
    })
    return routerfile
}

// 注册所有引入模块的路由
function registryRoute(routerfile) {
    routerfile.forEach(item => {
        let tmpPath = __dirname+ '/' + item
        let obj =require(tmpPath)
        for(let i in obj){
            let tmpArr = i.split(' ')
            // console.log(tmpArr);
            let rMethod = tmpArr[0]
            let rPath = tmpArr[1];
            let rFunction = obj[i]
            // 判断请求方式
            if(rMethod == 'get'){ 
                router.get(rPath,rFunction)
            }else if(rMethod == 'post'){
                router.post(rPath,rFunction)
            }else if(rMethod == 'delete'){
                router.delete(rPath,rFunction)
            }else if(rMethod == 'put'){
                router.put(rPath,rFunction)
            }
        }  
    });
}

let routerFiles = getRouteFile(__dirname)
registryRoute(routerFiles)


module.exports = router